package better;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {

    //获取连接
    private static Connection connection = null;

    //定义静态变量，获取配置文件的信息
    private static String driver = null;
    private static String user = null;
    private static String password = null;
    private static String url = null;


    //把获取连接，得到连接方法，获取结果集，获取配置文件和加载驱动放到静态代码块里面
    //因为这些代码只需要执行一次就够了，不需要重复执行
    static {
        InputStream rs = JDBCUtils.class.getClassLoader().getResourceAsStream("better/jdbc.properties");
        Properties properties = new Properties();
        try {
            properties.load(rs);
            driver = properties.getProperty("driver");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            url = properties.getProperty("url");
        } catch (IOException e) {
            e.printStackTrace();
        }

        //加载驱动
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }

    /**
     * 有两个方法一定需要
     * 1，获取连接
     * 2，关闭资源
     */

    //静态方法获取获取连接，方便程序在获取连接时直接调用这个类的静态方法即可。
    //就算改变了数据库，修改配置文件即可
    public static Connection getConnection() throws Exception {
        connection = DriverManager.getConnection(url, user, password);
        return connection;
    }

    //此处不用connection,是因为上面定义了静态变量connection，用的话会引起歧义，所以此地用con
    public static void close(Connection con, Statement statement, ResultSet resultSet) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
